﻿using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Xml;

namespace UnityEngine.UI
{
    [RequireComponent(typeof(ToggleGroup))]
    public class TreeView : TreeNodeContainer, IComparer<TreeNode>
    {
        /// <summary>
        /// 模板节点
        /// </summary>
        [SerializeField]
        private TreeNode m_templateNode;
        public TreeNode TemplateNode
        {
            get
            {
                return m_templateNode;
            }
        }
        /// <summary>
        /// 滚动区域
        /// </summary>
        [SerializeField]
        private ScrollRect m_areaScrollRect;
        /// <summary>
        /// 常规文字颜色
        /// </summary>
        [SerializeField]
        private Color m_normalTextItemColor = Color.white;
        public Color NormalTextItemColor
        {
            get
            {
                return m_normalTextItemColor;
            }
        }
        /// <summary>
        /// 选择时文字颜色
        /// </summary>
        [SerializeField]
        private Color m_selectTextItemColor = Color.green;
        public Color SelectTextItemColor
        {
            get
            {
                return m_selectTextItemColor;
            }
        }

        private ToggleGroup m_nodeToggleGroup;
        public ToggleGroup NodeToggleGroup
        {
            get
            {
                if(!m_nodeToggleGroup)
                {
                    m_nodeToggleGroup = GetComponent<ToggleGroup>();
                }
                return m_nodeToggleGroup;
            }
        }

        private RectTransform m_transNodeRoot;
        protected RectTransform TransNodeRoot
        {
            get
            {
                if(!m_transNodeRoot && m_templateNode)
                {
                    m_transNodeRoot = m_templateNode.TransCached.parent as RectTransform;
                }
                return m_transNodeRoot;
            }
        }

        public override RectTransform ContainerRoot
        {
            get
            {
                return TransNodeRoot;
            }
        }

        public override TreeView OwnerView
        {
            get
            {
                return this;
            }
        }
        /// <summary>
        /// 节点打开关闭事件
        /// </summary>
        public event System.Action<TreeNode, bool> OnTreeNodeSwitch;
        /// <summary>
        /// 节点选择取消事件
        /// </summary>
        public event System.Action<TreeNode, bool> OnTreeNodeSelect;

        protected override void Awake()
        {
            base.Awake();
            if(m_templateNode)
            {
                m_templateNode.GoCached.SetActive(false);
            }
        }

        protected override void AddNodeToList(TreeNode node)
        {
            base.AddNodeToList(node);
            node.ActiveNode(true);
        }

        public void CallTreeNodeSwitch(TreeNode node, bool expand)
        {
            ClampScrollRect();
            if(OnTreeNodeSwitch != null)
            {
                OnTreeNodeSwitch.Invoke(node, expand);
            }
        }

        public void CallTreeNodeSelect(TreeNode node, bool select)
        {
            if(OnTreeNodeSelect != null)
            {
                OnTreeNodeSelect.Invoke(node, select);
            }
        }

        public void ClampScrollRect()
        {
            if(m_areaScrollRect)
            {
                StartCoroutine(WaitClampScrollRect());
            }
        }

        IEnumerator WaitClampScrollRect()
        {
            yield return new WaitForEndOfFrame();
            Vector2 pos = m_areaScrollRect.normalizedPosition;
            pos.x = Mathf.Clamp01(pos.x);
            pos.y = Mathf.Clamp01(pos.y);
            m_areaScrollRect.normalizedPosition = pos;
        }

        public int Compare(TreeNode x, TreeNode y)
        {
            return x.TransCached.GetSiblingIndex() - y.TransCached.GetSiblingIndex();
        }

        /// <summary>
        /// 通过xml数据根节点填充节点
        /// </summary>
        /// <param name="root"></param>
        public void InitNodesFromXml(XmlNode root)
        {
            if(root != null)
            {
                ClearNodes();
                ClampScrollRect();
                foreach(XmlElement element in root.ChildNodes)
                {
                    FillElement(this, element);
                }
            }
        }

        void FillElement(TreeNodeContainer container, XmlElement element)
        {
            if(element != null)
            {
                var treeNode = container.AddChildNode();
                treeNode.OnBeginSetParam();
                foreach(XmlAttribute attr in element.Attributes)
                {
                    if(attr != null)
                    {
                        treeNode.SetParam(attr.Name, attr.Value);
                    }
                }
                treeNode.OnSetAllParam();
                foreach(XmlElement childElement in element.ChildNodes)
                {
                    FillElement(treeNode, childElement);
                }
            }
        }

        /// <summary>
        /// 通过xml路径填充tree
        /// </summary>
        /// <param name="xmlPath"></param>
        public void InitNodesFromXml(string xmlPath)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            using(XmlReader reader = XmlReader.Create(xmlPath, settings))
            {
                doc.Load(reader);
            }
            InitNodesFromXml(doc.DocumentElement);
        }
    }
}
